import { useEffect, useState } from 'react'
import { useThrottleFn } from '@/library/hooks/use-throttle-fn'
import { DemoBlock } from '@/library/widgets/DemoBlock'
import Tabs from '@/library/gallery/components/Tabs'
import styles from './style.module.scss'

const generateRandomString = (length: number): string => {
  let result = ''
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length)
    result += characters.charAt(randomIndex)
  }
  return result
}

const tabItems = [
  { key: '1', title: '第一项', text: generateRandomString(800) },
  { key: '2', title: '第二项', text: generateRandomString(700) },
  { key: '3', title: '第三项', text: generateRandomString(1000) },
  { key: '4', title: '第四项', text: generateRandomString(1600) },
]

const tabHeight = 42

export default () => {
  const [activeKey, setActiveKey] = useState('1')

  const { run: handleScroll } = useThrottleFn(
    () => {
      let currentKey = tabItems[0].key
      for (const item of tabItems) {
        const element = document.getElementById(`anchor-${item.key}`)
        if (!element) continue
        const rect = element.getBoundingClientRect()
        if (rect.top <= tabHeight) {
          currentKey = item.key
        } else {
          break
        }
      }
      setActiveKey(currentKey)
    },
    {
      leading: true,
      trailing: true,
      wait: 100,
    },
  )

  useEffect(() => {
    window.addEventListener('scroll', handleScroll)
    return () => {
      window.removeEventListener('scroll', handleScroll)
    }
  }, [])

  return (
    <>
      <DemoBlock title="作为页面滚动的导航" padding="0">
        <div className={styles['tabs-container']}>
          <Tabs
            activeKey={activeKey}
            onChange={(key) => {
              document.getElementById(`anchor-${key}`)?.scrollIntoView()
              window.scrollTo({
                top: window.scrollY - tabHeight,
              })
            }}
          >
            {tabItems.map((item) => (
              <Tabs.Tab title={item.title} key={item.key} />
            ))}
          </Tabs>
        </div>
        <div className={styles.content2}>
          {tabItems.map((item) => (
            <div key={item.key}>
              <h2 id={`anchor-${item.key}`}>{item.title}</h2>
              <div>{item.text}</div>
            </div>
          ))}
        </div>
      </DemoBlock>
    </>
  )
}
